import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Badge } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import ManageList from '@/components/ManageList';
import SelectForm from '@/components/SelectForm';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import AntdFormItem from '@/components/AntdFormItem';
import SearchSelect from '@/components/SearchSelect';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import FileReader from '@/components/FileReader';
import DriverPaperDetail from './DriverPaperDetail';
import { queryDict, vitifyCheck, formatPrice } from '@/utils/common';
import { columnsDriver, supplierColumns } from '@/pages/Common/common';
import { allDictList, billStateOnlyReadList, billStateList } from '@/utils/constans';
import prompt from '@/components/Prompt';
import {
  selectDriverPaperList,
  allDispatchType,
  codes,
  routeUrl,
  dispatchDriverPaper,
  formate,
  renderTableAdSearch,
  renderTableAdSelect,
  allUrl,
  formateNOSecond,
  selectPaperDetail,
  saveAllValues,
} from './utils';
const { confirm } = Modal;

@ManageList
@connect(({ driverPaper, component, loading }) => ({
  driverPaperList: driverPaper.driverPaperList,
  formValues: driverPaper.formValues,
  searchValue: component.searchValue,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.list],
}))
@Form.create()
export default class DriverPaperList extends Component {
  state = {
    visible: false,
    detailId: '',
    company: [],
    drivers: [],
    selectedRows: [],
    recordStatus: '',
  };
  className = 'DriverPaperList';

  columns = [
    {
      title: '单号',
      dataIndex: 'papersNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '状态',
      dataIndex: 'billStatus',
      render: (text, record) =>
        renderTableAdSelect({
          props: this.props,
          value: text ? text : record.status,
          data: billStateOnlyReadList,
        }),
      width: 100,
    },
    {
      title: '司机',
      dataIndex: 'driverName',
    },
    {
      title: '所属公司',
      dataIndex: 'mdsCompanyName',
      width: 210,
    },
    {
      title: '证件类型',
      dataIndex: 'papersType',
      width: 100,
      render: text =>
        renderTableAdSelect({ props: this.props, value: text, key: allDictList.papersType }),
    },
    {
      title: '证件编号',
      dataIndex: 'papersNumber',
    },

    {
      title: '有效期',
      dataIndex: 'effeTimeBegin',
      width: 200,
      render: (_, record) => {
        const { expiryStartTime, expiryEndTime } = record;
        const text = expiryStartTime ? `${expiryStartTime}~${expiryEndTime}` : '';
        return <span title={text}>{text}</span>;
      },
    },
    {
      title: '费用',
      dataIndex: 'feeCost',
      render: text => <span title={formatPrice(text)}>{formatPrice(text)}</span>,
    },
    {
      title: '附件',
      dataIndex: 'attaQuantity',
      width: 80,
      render: (text, record) =>
        text &&
        Number(text) > 0 && (
          <Badge className="cus_badge" count={text}>
            <div className="head-example">
              <FileReader
                type="list"
                count={text}
                urlType="tms"
                params={{ bizId: record.id, fileBizType: 'PAPERS' }}
              />
            </div>
          </Badge>
        ),
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => renderTableAdSearch({ props: this.props, value: text }),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => moment(text).format(formateNOSecond),
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => renderTableAdSearch({ props: this.props, value: text }),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => moment(text).format(formateNOSecond),
    },
  ];

  componentWillMount() {
    const allDict = [allDictList.papersType];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    selectDriverPaperList({ props: this.props });
  }

  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form } = this.props;
    const props = { props: this.props };
    this.setState({
      company: [],
      drivers: [],
    });
    saveAllValues({ payload: { formValues: {} }, ...props });
    selectDriverPaperList({ ...props });
  };

  /**
   * form 查找条件 查询
   */
  handleSearch = formValues => {
    if (!formValues) return;
    const { company, drivers } = this.state;
    const { mdsCompanyId, driverId, ...params } = formValues;
    if (company.length > 0) {
      params.mdsCompanyId = company[0].customerCode;
    }
    if (drivers.length > 0) {
      params.driverId = drivers[0].id;
    }
    saveAllValues({ props: this.props, payload: { formValues } });
    selectDriverPaperList({ props: this.props, payload: params });
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    const { formValues } = this.props;
    selectDriverPaperList({ payload: { ...formValues, ...param }, props: this.props });
  };

  /**
   *  查看详情
   */
  showDetail = (e, record) => {
    e.stopPropagation();
    const recordStatus = record.billStatus ? record.billStatus : record.status;
    this.handleStateChange([{ detailId: record.id }, { recordStatus }, { visible: true }]);
  };

  //新建
  handleAdd = () => {
    router.push(routeUrl.add);
  };

  //编辑
  handleEdit = () => {
    const { detailId } = this.state;
    this.handleStateChange([{ visible: false }]);
    router.push(`${routeUrl.edit}/${detailId}`);
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };

  // 删除
  delPaper = () => {
    const { dispatch, formValues } = this.props;
    const { detailId } = this.state;
    const _this = this;
    confirm({
      title: '确定删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: allDispatchType.delete,
          payload: { id: detailId },
          callback: () => {
            _this.handleStateChange([{ visible: false }]);
            selectDriverPaperList({ props: _this.props, payload: formValues });
          },
        });
      },
    });
  };

  /**
   * 生成账单
   */
  generatedBills = () => {
    const { dispatch, formValues } = this.props;
    const { selectedRows } = this.state;
    const checkBill = this.checkBill();
    if (!checkBill) return;
    dispatch({
      type: allDispatchType.genBills,
      payload: { ids: selectedRows.map(v => v.id) },
      callback: data => {
        if (!data) return;
        this.setState({
          selectedRows: [],
        });
        selectDriverPaperList({ props: this.props, payload: formValues });
        //跳转到账单的编辑页面
        router.push(`${routeUrl.billEdit}/${data}`);
      },
    });
  };

  /**
   * 生成账单校验 状态已提交，同一公司
   */

  checkBill = () => {
    const { selectedRows } = this.state;
    const mdsCompanyName = vitifyCheck({
      selectedRows,
      key: 'mdsCompanyName', // ownCompanyName
      warn: '所选记录必须所属公司相同！',
    });
    if (!mdsCompanyName) return false;
    return true;
  };
  selectAll = () => {
    const { dispatch, formValues } = this.props;
    dispatch({
      type: 'driverPaper/selectAll',
      payload: formValues,
      callback: data => {
        this.setState({
          selectedRows: [],
        });
        if (!data) return;
        selectDriverPaperList({ props: this.props, payload: formValues });
        //跳转到账单的编辑页面
        router.push(`${routeUrl.billEdit}/${data}`);
      },
    });
  };
  render() {
    const {
      form,
      form: { getFieldDecorator },
      loading,
      driverPaperList,
    } = this.props;

    const { isMobile, visible, detailId, selectedRows, recordStatus } = this.state;

    const commonParams = {
      getFieldDecorator,
    };
    const firstFormItem = (
      <AntdFormItem label="单号" code="papersNo" {...commonParams}>
        <AntdInput />
      </AntdFormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="状态" code="billStatus" {...commonParams}>
        <AdSelect isExist={true} data={billStateList} mode="multiple" />
      </AntdFormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <AntdFormItem label="司机" code="driverId" {...commonParams}>
          <SearchSelect
            multiple={false} // 是否多选
            dataUrl="tms/tms-driver/selectList"
            url="tms/tms-driver/viewDetails"
            selectedData={this.state.drivers} // 选中值
            columns={columnsDriver} // 表格展示列
            onChange={values => this.getValue(values, 'drivers')} // 获取选中值
            id="driverPaper_list_3"
            scrollX={500}
            allowClear={true}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="所属公司" code="mdsCompanyId" {...commonParams}>
          <SearchSelect
            dataUrl={allUrl.companyList}
            selectedData={this.state.company} // 选中值
            multiple={false} // 是否多选
            showValue="customerName"
            searchName="customerName"
            columns={supplierColumns} // 表格展示列
            onChange={values => this.getValue(values, 'company')} // 获取选中值
            scrollX={400}
            id="driverPaper_list_1"
            allowClear={true}
          />
        </AntdFormItem>,
        <AntdFormItem label="证件类型" code="papersType" {...commonParams}>
          <AdSelect payload={{ code: allDictList.papersType }} />
        </AntdFormItem>,
        <AntdFormItem label="证件编号" code="papersNumber" {...commonParams}>
          <AntdInput />
        </AntdFormItem>,
      ],
      ['operatorButtons'],
    ];

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
      code: codes.select,
    };

    const tableButtonsParams = {
      handleAdd: this.handleAdd,
      code: codes.add,
      selectedLength: selectedRows.length,
      pagination: driverPaperList.pagination,
      code: codes.bill,
      selectAll: this.selectAll,
      buttons: (
        <Fragment>
          <AdButton
            disabled={!selectedRows.length > 0}
            onClick={() => this.generatedBills()}
            text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
            code={codes.bill}
          />
        </Fragment>
      ),
    };
    // 详情 参数
    const _status = recordStatus === 'CONFIRM' || recordStatus === 'WAIT';
    const rightDrawParams = {
      isMobile,
      visible,
      title: '司机证件详情',
      code: codes.showDetail,
      closeDetail: this.handleStateChange.bind(this, [{ visible: false }]),
      buttons: (
        <span>
          <AdButton
            onClick={() => this.delPaper()}
            disabled={!_status}
            text="删除"
            code={codes.delete}
            ghost
            type="danger"
          />
          <AdButton
            onClick={this.handleEdit}
            style={{ marginLeft: 8 }}
            disabled={!_status}
            type="primary"
            text="编辑"
            code={codes.edit}
          />
        </span>
      ),
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          loading={loading}
          data={driverPaperList}
          columns={this.columns}
          onPaginationChange={this.handleStandardTableChange}
          className={this.className}
          code={codes.page}
          expandForm={false}
          disabledSelectedRows={{ code: ['billStatus', 'status'], value: ['CONFIRM', 'WAIT'] }}
          selectedRows={selectedRows}
          onSelectRow={selectedRows => {
            this.handleStateChange([{ selectedRows }]);
          }}
          getCheckboxProps={record => {
            const status = record.billStatus ? record.billStatus : record.status;
            const checked = status === 'CONFIRM' || status === 'WAIT';
            return !checked;
          }}
        />
        <RightDraw {...rightDrawParams}>
          <DriverPaperDetail id={detailId} />
        </RightDraw>
      </Fragment>
    );
  }
}
